package async;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;

import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;

public class WriteListener {

	public void handleWrite(WritableByteChannel channel, Message message) throws IOException {
		
		//prepare buffer
		int messagelength = message.getSerializedSize();
		int totalLength = messagelength +  CodedOutputStream.computeRawVarint32Size(messagelength);
		byte[] buf = new byte[totalLength];
		
		//write length
		CodedOutputStream cos = CodedOutputStream.newInstance(buf);
		cos.writeRawVarint32(messagelength);
		cos.flush();
		
		//write buffer
		ByteBuffer b = ByteBuffer.wrap(buf);
		b.put(message.toByteArray());
		b.flip();
		channel.write(b);
		
	}
	
}
